package com.linewell.license.demo.security;

import com.alibaba.fastjson.JSONObject;
import com.linewell.license.demo.utils.CurrentRequestUtils;
import com.linewell.license.platform.common.model.result.ResultCodeBaseConstants;
import com.linewell.license.platform.common.model.result.ResultObjectModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
* @author
* Company:
* Createtime : 2018年9月11日 下午3:40:02
* Description : 认证失败后的动作
*/
@Component
public class SecurityLoginFailureHandler implements AuthenticationFailureHandler {

	private Logger logger = LoggerFactory.getLogger(SecurityLoginFailureHandler.class);

	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
		this.handler(request, response, e);
	}

	public void handler(HttpServletRequest request, HttpServletResponse response, Exception e) throws IOException , ServletException {
		logger.error(e.getMessage() , e);
		request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
		if(!CurrentRequestUtils.isAjaxRequest()) {
			response.sendRedirect(CurrentRequestUtils.getRequestContextPath(request)+"/login.html?error=1");
			return;
        }
		//如果抛的是密码错误异常，将密码错误次数加入session，当次数达到两次
		ResultObjectModel<Object> result = new ResultObjectModel<>(ResultCodeBaseConstants.FAIL, e.getMessage() , null);
		response.getWriter().println(JSONObject.toJSONString(result));
	}

}
